import { Directive, Input, Output, EventEmitter } from '@angular/core';
import { CdkDragDrop, CdkDrag, CdkDropList, moveItemInArray } from '@angular/cdk/drag-drop';
import { LayoutContainer } from '../models/layout.models';

@Directive({
  selector: '[appContainerDragSort]',
  standalone: true,
  // imports: [CdkDrag, CdkDropList]
})
export class ContainerDragSortDirective {
  @Input() containers: LayoutContainer[] = [];
  @Output() containersReorder = new EventEmitter<LayoutContainer[]>();

  onContainerDrop(event: CdkDragDrop<LayoutContainer[]>) {
    if (event.previousContainer === event.container) {
      // 在同一列表中重新排序
      moveItemInArray(this.containers, event.previousIndex, event.currentIndex);

      // 更新排序字段
      this.containers.forEach((container, index) => {
        container.order = index;
      });

      this.containersReorder.emit([...this.containers]);
    }
  }

  getContainerDragData(container: LayoutContainer) {
    return {
      type: 'container',
      id: container.id,
      containerType: container.type
    };
  }
}
